package ffm

import (
	"log"
	"os"
	"os/exec"
	"strings"
)

//依赖ffmpeg工具

// TakeVideoFirstFrame 截取视频第一帧保存为图片
func TakeVideoFirstFrame(videoPath string) (string, error) {
	//videoPath := "6f3c46a7d14a520adfddc79756082d02.mp4" // 输入视频文件
	imagePath, imageName := getImagePath(videoPath) // 输出目录，存放提取出的视频帧

	// 创建输出目录
	err := os.MkdirAll(imagePath, os.ModePerm)
	if err != nil {
		log.Println("截取视频第一帧保存为图片:", err.Error())
		return imagePath, err
	}

	// 构造FFmpeg命令
	//cmd := exec.Command("ffmpeg", "-i", videoPath, "-frames:v", "1", imagePath+imageName)
	cmd := exec.Command("ffmpeg", "-i", videoPath, "-ss", "00:00:01", "-vframes", "1", imagePath+imageName)

	// 执行命令
	err = cmd.Run()
	if err != nil {
		log.Println("截取视频第一帧保存为图片:", err.Error())
		return imagePath, err
	}
	return imagePath, err
}

func getImagePath(path string) (string, string) {
	pathArr := strings.Split(path, "/")
	path = ""
	fileName := ""
	for k, v := range pathArr {

		if k+1 == len(pathArr) {
			fileName = v
		} else {
			path += v + "/"
		}

	}
	fileName = strings.Split(fileName, ".")[0] + ".png"

	return path, fileName

}
